

package cn.shengchao.examstar.distribute.infrastrure.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.base.enums.DisEnableStatusEnum;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.distribute.infrastrure.mapper.DistributeContentInfoMapper;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeContentInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeContentInfoService;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeContentBatchDto;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeContentDto;
import cn.shengchao.examstar.rpc.distribute.req.CourseDistributeQueryPage;
import cn.shengchao.examstar.rpc.distribute.req.CourseDistributeUserQueryPage;
import cn.shengchao.examstar.rpc.distribute.resp.CourseDistributeForUserRespEntity;
import cn.shengchao.examstar.rpc.distribute.resp.CourseDistributeRespEntity;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DistributeContentInfoServiceImpl extends ServiceImpl<DistributeContentInfoMapper, DistributeContentInfo> implements DistributeContentInfoService {
    @Override
    public PageResult<CourseDistributeRespEntity> getCourseDistributePageList(CourseDistributeQueryPage courseDistributeQueryPage) {
        Page<Object> page = PageHelper.startPage(courseDistributeQueryPage.getPage(), courseDistributeQueryPage
            .getSize());
        List<CourseDistributeRespEntity> courseDistributeRespEntities = baseMapper
            .selectDistributeContentsCoursePageQuery(courseDistributeQueryPage);
        return PageResult.of(page.getTotal(), courseDistributeRespEntities);
    }
    @Override
    public PageResult<CourseDistributeForUserRespEntity> getCourseDistributeForUserPageList(CourseDistributeUserQueryPage courseDistributeQueryPage) {
        Page<Object> page = PageHelper.startPage(courseDistributeQueryPage.getPage(), courseDistributeQueryPage
                .getSize());
        List<CourseDistributeForUserRespEntity> courseDistributeRespEntities = baseMapper
                .selectDistributeContentsCourseForUserPageQuery(courseDistributeQueryPage);
        return PageResult.of(page.getTotal(), courseDistributeRespEntities);
    }
    @Transactional
    @Override
    public void clearProducts(DistributeContentBatchDto distributeContentBatchDto) {
        List<Long> contentIds=distributeContentBatchDto.getContentDtoList().stream().map(DistributeContentDto::getProductId).toList();
        if (CollUtil.isNotEmpty(contentIds)){
            baseMapper.update(new DistributeContentInfo(), Wrappers.lambdaUpdate(DistributeContentInfo.class)
                    .eq(DistributeContentInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                    .eq(DistributeContentInfo::getAuthorUserId, distributeContentBatchDto.getAuthorUserId())
                    .in(DistributeContentInfo::getContentId, contentIds)
                    .set(DistributeContentInfo::getValidEndTime, new Date())
                    .set(DistributeContentInfo::getDataStatus, DistributeDataStatusEnum.STATUS_HIS.getStatus()));
        }
    }

    @Transactional
    @Override
    public void registerNewProducts(DistributeContentBatchDto distributeContentBatchDto) {
        if (distributeContentBatchDto != null && CollUtil.isNotEmpty(distributeContentBatchDto.getContentDtoList())) {
            List<Long> productIdList = distributeContentBatchDto.getContentDtoList()
                .stream()
                .map(DistributeContentDto::getProductId)
                .toList();
            List<DistributeContentInfo> contentInfoList = list(Wrappers.lambdaQuery(DistributeContentInfo.class)
                .eq(DistributeContentInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                .in(DistributeContentInfo::getContentId, productIdList));

//            if (contentInfoList != null){
//                List<DistributeContentInfo> notBelongContentList=contentInfoList.stream().filter(a->a.getContentDistributeUserId()!=null&&!a.getContentDistributeUserId().equals(distributeContentBatchDto.getDistributeUserId())).toList();
//                if (CollUtil.isNotEmpty(notBelongContentList)) {
//                    throw new RuntimeException("登记单里有产品已被其他人登记，不能重复登记");//
//                }
//            }
            //更新老的数据为历史状态
            List<DistributeContentInfo> contentInfoList1=contentInfoList.stream().filter(b->b.getAuthorUserId().equals(distributeContentBatchDto.getAuthorUserId())).toList();
            if (CollUtil.isNotEmpty(contentInfoList1)){
                contentInfoList1.forEach(a->{a.setDataStatus(DistributeDataStatusEnum.STATUS_HIS.getStatus());});
                updateBatchById(contentInfoList1);
            }
            //保存新的数据
            List<DistributeContentInfo> contentInfos = new ArrayList<>();
            for (DistributeContentDto distributeContentDto : distributeContentBatchDto.getContentDtoList()) {
                DistributeContentInfo distributeContentInfo = new DistributeContentInfo();
                distributeContentInfo.setContentId(distributeContentDto.getProductId());
                distributeContentInfo.setContentName(distributeContentDto.getProductName());
                distributeContentInfo.setValidStartTime(new Date());
                distributeContentInfo.setValidEndTime(DateUtil.parse("2099-12-30","yyyy-MM-dd").toJdkDate());
                distributeContentInfo.setEnableStatus(DisEnableStatusEnum.ENABLE.getValue());
                distributeContentInfo.setDataStatus(DistributeDataStatusEnum.STATUS_CURT.getStatus());
                distributeContentInfo.setStablePercent(distributeContentDto.getStablePercent());
                distributeContentInfo.setAuthorUserId(distributeContentBatchDto.getAuthorUserId());
                distributeContentInfo.setContentDistributeUserId(distributeContentBatchDto.getDistributeUserId());
                contentInfos.add(distributeContentInfo);
            }
            saveBatch(contentInfos);
        }
    }

    @Override
    public Map<Long, String> checkContentPercent(DistributeContentBatchDto distributeContentBatchDto) {
        Map<Long, String> map = new HashMap<>();
        if (CollUtil.isNotEmpty(distributeContentBatchDto.getContentDtoList())){
            Long userId=distributeContentBatchDto.getDistributeUserId();
            List<DistributeContentInfo> distributeContentInfoList = list(Wrappers.lambdaQuery(DistributeContentInfo.class)
                    .in(DistributeContentInfo::getContentId, distributeContentBatchDto.getContentDtoList().stream().map(DistributeContentDto::getProductId).toList())
                    .eq(DistributeContentInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                    .ne(DistributeContentInfo::getContentDistributeUserId, userId));
            Map<Long,List<DistributeContentInfo>> map1 = distributeContentInfoList.stream().collect(Collectors.groupingBy(DistributeContentInfo::getContentId));
            Map<Long, BigDecimal> map2 = distributeContentBatchDto.getContentDtoList().stream().collect(Collectors.toMap(DistributeContentDto::getProductId, DistributeContentDto::getStablePercent));
            for (Long key:map2.keySet()){
               List<DistributeContentInfo> list=map1.get(key);
               BigDecimal sum=CollUtil.isNotEmpty(list)?map2.get(key).add(list.stream().map(DistributeContentInfo::getStablePercent).reduce(BigDecimal.ZERO, BigDecimal::add)):BigDecimal.ZERO;
               if (sum.doubleValue()>50){
                   map.put(key,list.get(0).getContentName());
               }
            }
            return map;
        }
        return Map.of();
    }
}
